package chapter25;

import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2019/2/28 10:38
 */
public class PatternTest {
    public static void main(String[] args) {

        replaceCat();

        String str3 = "hello      world        good";
        String regex3 = "\\s+";
        System.out.println(str3.replaceAll(regex3, " "));

        find();

        //language=RegExp
        String regex = "<(\\w+)>(.*)</\\1>";
        Pattern pattern = Pattern.compile(regex);

        String str = "abd.def.hello";
        String[] fields = str.split("\\.");
        System.out.println(Arrays.toString(fields));

        str = ",abc,,def,,";
        String[] fields2 = str.split(",");
        System.out.println(Arrays.toString(fields2));

        String regex2 = "\\d{8}";
        String str2 = "12345678";
        System.out.println(str2.matches(regex2));
    }

    public static void replaceCat() {
        Pattern pattern = Pattern.compile("cat");
        Matcher matcher = pattern.matcher("one cat, two cat, three cat");
        StringBuffer buffer = new StringBuffer();
        int foundNum = 0;
        while (matcher.find()) {
            matcher.appendReplacement(buffer, "dog");
            foundNum++;
            if (foundNum == 2) {
                break;
            }
        }
        matcher.appendTail(buffer);
        System.out.println(buffer);
    }

    public static void find() {
        String regex = "\\d{4}-\\d{2}-\\d{2}";
        Pattern pattern = Pattern.compile(regex);
        String str = "today is 2017-06-02, yesterday is 2017-06-01";
        Matcher matcher = pattern.matcher(str);
        while (matcher.find()) {
            System.out.println("find " + matcher.group() + " position: " + matcher.start() + "-" + matcher.end());
        }
    }
}
